package com.client;

import com.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @ClassName JoinRoom
 * @Description 加入房间功能
 * 传入当前帐号和主机帐号
 * @Author Zxeao
 * @Date 2021/12/22 上午1:59
 * @Version V1.0
 */
public class JoinRoom {

    private final String account;
    private final String host_account;

    public JoinRoom(String account, String host_account) {
        this.account = account;
        this.host_account = host_account;
    }

    public Client joinRoom() throws Exception{
        //加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //连接数据库
        Connection conn = DriverManager.getConnection(Config.JDBCURL, "zxeao", "123456");
        System.out.println("加入房间：数据库连接成功");

        //通过连接对象 获得Statement 对象
        String sql = String.format("SELECT ip FROM `account` WHERE account='%s'", host_account);

        PreparedStatement statement  = conn.prepareStatement(sql);

        //执行SQL
        ResultSet res = statement.executeQuery();

        if (res.next()){
            System.out.println("加入房间：成功找到主机IP"+res.getString(1));
            String sql1 = String.format("UPDATE `account` SET ip = '%s' WHERE account = '%s' ", res.getString(1), account);
            PreparedStatement statement1  = conn.prepareStatement(sql1);
            int res1 = statement1.executeUpdate();
            String iP = res.getString(1);
            //结束工作
            res.close();
            statement1.close();
            statement.close();
            conn.close();
            return new Client(host_account,iP);
        }else {
            System.out.println("加入房间失败");
            return null;
        }
    }
}
